/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.shop.shopconfig.web;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.web.shop.shopconfig.ShopConfigRestApi;
import org.opsli.api.wrapper.shop.shopconfig.ShopConfigModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.log.annotation.OperateLogger;
import org.opsli.core.log.enums.ModuleEnum;
import org.opsli.core.log.enums.OperationTypeEnum;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.shop.shopconfig.entity.ShopConfig;
import org.opsli.modulars.shop.shopconfig.service.IShopConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 店铺配置 Controller
 *
 * @author 17607080935
 * @date 2024-10-12 17:57:15
 */
@Api(tags = ShopConfigRestApi.TITLE)
@Slf4j
@ApiRestController("/{ver}/shop/shopconfig")
public class ShopConfigRestController extends BaseRestController<ShopConfig, ShopConfigModel, IShopConfigService>
        implements ShopConfigRestApi {


    /**
     * 店铺配置 查一条
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    @PreAuthorize("hasAuthority('shop_shopconfig_select')")
    @Override
    public ResultWrapper<ShopConfigModel> get(ShopConfigModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultWrapper.getSuccessResultWrapper(model);
    }

    @Override
    public String getBy(String tid, String name) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_ids", tid);
        queryWrapper.eq("name", name);
        ShopConfig s = IService.getOne(queryWrapper);
        return s.getValue();
    }

    /**
     * 店铺配置 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @PreAuthorize("hasAuthority('shop_shopconfig_select')")
    @Override
    public ResultWrapper<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<ShopConfig> queryBuilder = new WebQueryBuilder<>(IService.getEntityClass(), request.getParameterMap());
        Page<ShopConfig, ShopConfigModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);
        return ResultWrapper.getSuccessResultWrapper(page.getPageData());
    }

    @Override
    public ResultWrapper<List<Map<String, Object>>> listByDistance10(String lat, String lon, String id, String title) {
        return ResultWrapper.getSuccessResultWrapper(IService.listByDistance10(lat, lon, id, title));
    }

    /**
     * 检查名称是否存在
     *
     * @param name
     * @return
     */
    public boolean checkName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", name);
        queryWrapper.eq("org_ids", UserUtil.getUser().getTenantId());
        return IService.count(queryWrapper) > 0;
    }


    /**
     * 店铺配置 新增
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "新增店铺配置数据", notes = "新增店铺配置数据")
    @PreAuthorize("hasAuthority('shop_shopconfig_insert')")
    @OperateLogger(description = "新增店铺配置数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> insert(ShopConfigModel model) {
        // 调用新增方法

        if (checkName(model.getName())) {
            return ResultWrapper.getCustomResultWrapper(500, "操作失败,名称已存在");
        }
        IService.insert(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("新增店铺配置成功");
    }

    /**
     * 将默认的配置都加入到新租户里
     *
     * @param tenantId
     * @return
     */
    @Override
    public void insertByTenant(String tenantId, String title) {
        // 查询默认的配置
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_ids", "0");
        queryWrapper.eq("is_default", 1);
        List<ShopConfigModel> list = WrapperUtil.transformInstance(IService.list(queryWrapper), ShopConfigModel.class);
        for (ShopConfigModel shopConfig : list) {
            if (shopConfig.getName().equals("title")) {
                shopConfig.setValue(title);
            }
            shopConfig.setOrgIds(tenantId);
            shopConfig.setId(null);
            IService.insert(shopConfig);
        }

    }


    /**
     * 店铺配置 修改
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改店铺配置数据", notes = "修改店铺配置数据")
    @PreAuthorize("hasAuthority('shop_shopconfig_update')")
    @OperateLogger(description = "修改店铺配置数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @Override
    public ResultWrapper<?> update(ShopConfigModel model) {
        // 调用修改方法
        //名称跟以前的不一样。就去检查是否重名
        if (!IService.get(model.getId()).getName().equals(model.getName()) && checkName(model.getName())) {
            return ResultWrapper.getCustomResultWrapper(500, "操作失败,名称已存在");
        }
        IService.update(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("修改店铺配置成功");
    }


    /**
     * 店铺配置 删除
     *
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除店铺配置数据", notes = "删除店铺配置数据")
    @PreAuthorize("hasAuthority('shop_shopconfig_delete')")
    @OperateLogger(description = "删除店铺配置数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> del(String id) {
        IService.delete(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("删除店铺配置成功");
    }

    /**
     * 店铺配置 批量删除
     *
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除店铺配置数据", notes = "批量删除店铺配置数据")
    @PreAuthorize("hasAuthority('shop_shopconfig_delete')")
    @OperateLogger(description = "批量删除店铺配置数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultWrapper.getSuccessResultWrapperByMsg("批量删除店铺配置成功");
    }

    /**
     * 店铺配置 Excel 导出认证
     *
     * @param type    类型
     * @param request request
     */
    @ApiOperation(value = "Excel 导出认证", notes = "Excel 导出认证")
    @PreAuthorize("hasAnyAuthority('shop_shopconfig_export', 'shop_shopconfig_import')")
    @Override
    public ResultWrapper<String> exportExcelAuth(String type, HttpServletRequest request) {
        Optional<String> certificateOptional =
                super.excelExportAuth(type, ShopConfigRestApi.SUB_TITLE, request);
        if (!certificateOptional.isPresent()) {
            return ResultWrapper.getErrorResultWrapper();
        }
        return ResultWrapper.getSuccessResultWrapper(certificateOptional.get());
    }


    /**
     * 店铺配置 Excel 导出
     *
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PreAuthorize("hasAuthority('shop_shopconfig_export')")
    @OperateLogger(description = "店铺配置 导出Excel",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.SELECT, db = true)
    @Override
    public void exportExcel(String certificate, HttpServletResponse response) {
        // 导出Excel
        super.excelExport(certificate, response);
    }

    /**
     * 店铺配置 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     *
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @PreAuthorize("hasAuthority('shop_shopconfig_import')")
    @OperateLogger(description = "店铺配置 Excel 导入",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

}